package com.gensdai.leliang.wxapi;

import com.gensdai.leliang.AppApplication;
import com.gensdai.leliang.R;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;

public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {

    public static final String CODE_SUCCESS = "0";
    public static final String CODE_CANCEL = "-2";
    public static final String CODE_FAILED = "-1";

    public static final String PREPERORDER = "preperOrder";
    public static final String DETAILORDER = "detailOrder";
    public static final String INDENTORDER = "indentOrder";

    public static final String TAG ="WXPayEntryActivity";

    private static final int TIMELINE_SUPPORTED_VERSION = 0x21020001;

    private IWXAPI api;

    String payType;
    String orderId;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_null);
        api = WXAPIFactory.createWXAPI(this, AppApplication.APPID);
        getExtData(getIntent());
        api.handleIntent(getIntent(), this);
    }

    private void getExtData(Intent it){
        String data = it.getStringExtra("_wxapi_payresp_extdata");
        if(!TextUtils.isEmpty(data)){
            String[] datas = data.split("#");
            payType = datas[0];
            if(datas.length > 1){
                orderId = datas[1];
            }
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        getExtData(intent);
        api.handleIntent(intent, this);
    }


    // 微信发送请求到第三方应用时，会回调到该方法
    @Override
    public void onReq(BaseReq req) {
        Log.d(TAG,"onReq,errCode=");
    }

    // 第三方应用发送到微信的请求处理后的响应结果，会回调到该方法
    @Override
    public void onResp(BaseResp resp) {
        Log.d(TAG,"onResp,onResp");
        if(resp.getType()==ConstantsAPI.COMMAND_PAY_BY_WX){
            Log.d(TAG,"onPayFinish,errCode="+resp.errCode + "payType" + payType + "orderId" + orderId);
            Intent intent  = new Intent(payType);
            intent.putExtra("orderid", orderId);
            intent.putExtra("type", resp.errCode+"");
            LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
            this.finish();
        }
    }
}
